import { request } from '@/utils/request'

function getVersion(query) {
	let params = {
		method: 'GET',
		url: `appVersion/findByVersion`,
		data: query
	}
	return request(params)
}
 
function update(fileName) {
	let downURL =  fileName;
	console.log('下载地址', downURL);
	//后台显示进度条
	let dtask = plus.downloader.createDownload(
		downURL, {},
		function(d, status) {
			//下载完成
			uni.showModal({
				title: "更新提示",
				content: "新版本已经准备好，是否更新应用？",
				success: (res) => {
					if (res.confirm) {
						install(d, status);
					}
				},
			});
		}
	);
	start(dtask);
};
 
function start(dtask) {
	try {
		dtask.start(); //开启下载任务
		let prg = 0;
		let showLoading = plus.nativeUI.showWaiting("正在下载");
		dtask.addEventListener("statechanged", function(task, status) {
			switch (task.state) {
				case 1:
					showLoading.setTitle("正在下载");
					break;
				case 2:
					showLoading.setTitle("已连接到服务器");
					break;
				case 3:
					prg = parseInt(
						(parseFloat(task.downloadedSize) /
							parseFloat(task.totalSize)) *
						100
					);
					showLoading.setTitle("  正在下载" + prg + "%  ");
					break;
				case 4:
					plus.nativeUI.closeWaiting();
					break;
			}
		});
 
	} catch (err) {
		plus.nativeUI.closeWaiting();
		uni.showToast({
			title: "更新失败",
			mask: false,
			duration: 1500,
		});
	}
};
 
function install(d, status) {
	//下载完成
	if (status === 200) {
		plus.runtime.install(d.filename, {
			force: false
		}, function() {
			plus.nativeUI.closeWaiting();
			plus.nativeUI.alert("应用资源更新完成！是否重启应用！", function() {
				plus.runtime.restart();
			});
		}, function(e) {
			plus.nativeUI.closeWaiting();
			console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
			plus.nativeUI.alert("安装wgt文件失败[" + e.code + "]：" + e.message);
		});
	} else {
		uni.showToast({
			title: "下载失败",
			mask: false,
			duration: 1500,
		});
	}
};
 
function close(version) {
	try {
		console.log( '保存要跳过的版本', version)
	    uni.setStorageSync('skip_version', version);
	} catch (e) {
	    // error
	}
};
 
function signOut() {
	// #ifdef APP-PLUS
	plus.runtime.quit();
	// #endif
}
 
export default{
	getAppByVersion(curversion, back) {
		console.log("came in", curversion);
		let params = {};
		if (uni.getSystemInfoSync().platform == "ios") {
			params = {
				type: 2,
				version: curversion,
			};
		} else {
			params = {
				type: 1,
				version: curversion,
			};
		}
		
		getVersion(params).then(function(res) {
			console.log('version res');
			if (res.code == 200 && res.msg) {
				let result = res.msg; 
				if (result != '已是最新版本') {
					console.log('有新版本要更新', res.data);
					if (uni.getSystemInfoSync().platform != "ios") {
						plus.nativeUI.confirm(res.msg, function(e) {
							console.log(e); 
							if (e.index == 0) {
								console.log('update');
								update(res.data);
							} else if (result.strategy == 'force') {
								signOut(res.data);
							} else if (result.strategy == 'recommend') {
								close(res.data);
							}
						}, {
							"title": "新版本",
							"buttons": ["立即更新", result.strategy == 'force' ? "退出应用" : "暂不更新"]
						});
					}
					else
					{
						uni.showModal({
							title:"更新提示",
							content: "请点击按钮复制链接，粘贴到Safari浏览器打开，下载最新版本",
							confirmText: "点击复制",
							showCancel:false,
							success:()=>{
								uni.setClipboardData({
									data:"https://xxxx.xxxxx.xxxx/upload/peisong/index.html",
									success:()=>{
										uni.showToast({
											title:"复制链接成功，请粘贴到Safari浏览器打开"
										})
									}
								})
							}
						});
					}
				} else if (!back) {
					plus.nativeUI.alert("当前已是最新版本！"+params.version);
				}
			}
			else if (res.code != 200)
			{
				console.log('error');
				uni.showToast({
					title: res.msg,
					icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
					duration: 3000    //持续时间为 2秒
				});
			}else if (!back) {
					plus.nativeUI.alert("当前已是最新版本！"+params.version);
			}
		});
		
	},
	getVersion
}